package com.console;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

/**
 * 咋说呢，写的的确不错，但是如果根据这种思路重新 写一遍的话 代价太大了。
 */
public class HackerConsole extends JFrame {
    private JPanel matrixPanel;
    private JTextArea consoleArea;
    private Random random = new Random();
    private ArrayList<MatrixColumn> columns = new ArrayList<>();
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&*";
    private int typingSpeed = 10; // 更快的打字速度
    private boolean isBlinking = false;
    private Color textColor = new Color(0, 255, 0);
    private Timer blinkTimer;
    private int currentMessageSet = 0;

    public HackerConsole() {
        setTitle("Advanced Hacking Interface v2.0");
        setSize(1200, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setUndecorated(true); // 无边框效果

        // 设置背景为黑色
        setBackground(new Color(0, 0, 0, 240));

        JLayeredPane layeredPane = new JLayeredPane();
        layeredPane.setPreferredSize(new Dimension(1200, 800));

        // 矩阵雨效果面板
        matrixPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                g2d.setColor(new Color(0, 0, 0, 240));
                g2d.fillRect(0, 0, getWidth(), getHeight());
                drawMatrix(g2d);
            }
        };
        matrixPanel.setOpaque(false);
        matrixPanel.setBounds(0, 0, 1200, 800);

        // 控制台区域
        consoleArea = new JTextArea() {
            @Override
            public void paint(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                super.paint(g);
            }
        };
        consoleArea.setFont(new Font("Consolas", Font.BOLD, 14));
        consoleArea.setForeground(textColor);
        consoleArea.setBackground(new Color(0, 0, 0, 180));
        consoleArea.setEditable(false);
        consoleArea.setMargin(new Insets(20, 20, 20, 20));

        // 自定义滚动面板，隐藏滚动条
        JScrollPane scrollPane = new JScrollPane(consoleArea) {
            @Override
            protected void paintComponent(Graphics g) {
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(new Color(0, 0, 0, 180));
                g2d.fillRect(0, 0, getWidth(), getHeight());
                super.paintComponent(g);
            }
        };
        scrollPane.setBounds(50, 50, 1100, 700);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        scrollPane.setBorder(null);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        // 添加边框效果
        JPanel borderPanel = new JPanel(null) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setColor(new Color(0, 255, 0, 60));
                g2d.drawRect(45, 45, 1110, 710);
                g2d.drawRect(40, 40, 1120, 720);
            }
        };
        borderPanel.setBounds(0, 0, 1200, 800);
        borderPanel.setOpaque(false);

        layeredPane.add(matrixPanel, JLayeredPane.DEFAULT_LAYER);
        layeredPane.add(borderPanel, JLayeredPane.PALETTE_LAYER);
        layeredPane.add(scrollPane, JLayeredPane.MODAL_LAYER);

        add(layeredPane);

        // 添加ESC键退出功能
        KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
        Action escapeAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        };
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
                .put(escapeKeyStroke, "ESCAPE");
        getRootPane().getActionMap().put("ESCAPE", escapeAction);

        // 添加闪烁效果
        blinkTimer = new Timer(500, e -> {
            isBlinking = !isBlinking;
            if (isBlinking) {
                consoleArea.setForeground(textColor.darker().darker());
            } else {
                consoleArea.setForeground(textColor);
            }
        });
        blinkTimer.start();

        initializeMatrixColumns();
        startAnimation();
    }

    private void initializeMatrixColumns() {
        int columnWidth = 20;
        int numColumns = getWidth() / columnWidth;

        for (int i = 0; i < numColumns; i++) {
            columns.add(new MatrixColumn(i * columnWidth, random.nextInt(getHeight())));
        }
    }

    private void drawMatrix(Graphics g) {
        for (MatrixColumn column : columns) {
            column.draw(g);
        }
    }

    private void startAnimation() {
        Timer timer = new Timer(50, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (MatrixColumn column : columns) {
                    column.update();
                }
                matrixPanel.repaint();
            }
        });
        timer.start();
    }

    public void printMessage(String message) {
        // 实现打字机效果
        Timer timer = new Timer(typingSpeed, null);
        final int[] charIndex = {0};

        timer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (charIndex[0] < message.length()) {
                    String nextChar = String.valueOf(message.charAt(charIndex[0]));
                    consoleArea.append(nextChar);
                    // 自动滚动到底部
                    consoleArea.setCaretPosition(consoleArea.getDocument().getLength());
                    charIndex[0]++;
                } else {
                    consoleArea.append("\n");
                    // 自动滚动到底部
                    consoleArea.setCaretPosition(consoleArea.getDocument().getLength());
                    timer.stop();
                }
            }
        });
        timer.start();
    }

    // 矩阵列类
    private class MatrixColumn {
        private int x;
        private int y;
        private ArrayList<MatrixCharacter> characters = new ArrayList<>();

        public MatrixColumn(int x, int y) {
            this.x = x;
            this.y = y;
            initializeCharacters();
        }

        private void initializeCharacters() {
            int numChars = random.nextInt(5) + 5;
            for (int i = 0; i < numChars; i++) {
                characters.add(new MatrixCharacter());
            }
        }

        public void update() {
            y += 2;
            if (y > getHeight()) {
                y = -characters.size() * 20;
            }
        }

        public void draw(Graphics g) {
            int currentY = y;
            for (MatrixCharacter character : characters) {
                character.draw(g, x, currentY);
                currentY += 20;
            }
        }
    }

    // 矩阵字符类
    private class MatrixCharacter {
        private char character;
        private float brightness;

        public MatrixCharacter() {
            changeCharacter();
            brightness = random.nextFloat();
        }

        public void draw(Graphics g, int x, int y) {
            changeCharacter();
            // 添加颜色渐变效果
            float hue = (System.currentTimeMillis() % 3000) / 3000f;
            Color color = Color.getHSBColor(hue, 0.8f, brightness);
            g.setColor(color);
            g.drawString(String.valueOf(character), x, y);
        }

        private void changeCharacter() {
            character = CHARACTERS.charAt(random.nextInt(CHARACTERS.length()));
        }
    }

    private String generateRandomIP() {
        return random.nextInt(256) + "." + random.nextInt(256) + "." +
                random.nextInt(256) + "." + random.nextInt(256);
    }

    private String generateProgressBar(int progress, int style) {
        switch (style) {
            case 0: // 经典样式
                StringBuilder bar1 = new StringBuilder("[");
                for (int i = 0; i < 50; i++) {
                    bar1.append(i < progress / 2 ? "=" : " ");
                }
                bar1.append("] ").append(progress).append("%");
                return bar1.toString();

            case 1: // 高级样式
                StringBuilder bar2 = new StringBuilder("▕");
                for (int i = 0; i < 50; i++) {
                    bar2.append(i < progress / 2 ? "█" : "░");
                }
                bar2.append("▏ ").append(progress).append("%");
                return bar2.toString();

            case 2: // 动态样式
                char[] spinChars = {'⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'};
                return spinChars[progress % spinChars.length] + " Loading... " + progress + "%";

            default:
                return "[" + repeat("=",progress / 2) + repeat(" ",50 - progress / 2) + "] " + progress + "%";
        }
    }
    private static String repeat(String str, int num) {
        StringBuilder repeatStr = new StringBuilder();
        for (int i = 0; i < num; i++) {
            repeatStr.append(str);
        }
        return repeatStr.toString();
    }

    // 添加系统状态显示面板
    private JPanel createStatusPanel() {
        JPanel statusPanel = new JPanel(null) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

                // 绘制CPU使用率
                drawSystemStatus(g2d, "CPU", random.nextInt(100), 10, 10);
                // 绘制内存使用率
                drawSystemStatus(g2d, "MEM", random.nextInt(100), 10, 60);
                // 绘制网络状态
                drawNetworkStatus(g2d, 10, 110);
            }
        };
        statusPanel.setOpaque(false);
        statusPanel.setBounds(900, 50, 250, 200);
        return statusPanel;
    }

    private void drawSystemStatus(Graphics2D g2d, String label, int value, int x, int y) {
        g2d.setColor(new Color(0, 255, 0, 180));
        g2d.drawString(label + ": " + value + "%", x, y);
        g2d.drawRect(x, y + 5, 200, 20);
        g2d.setColor(new Color(0, 255, 0, 100));
        g2d.fillRect(x, y + 5, value * 2, 20);
    }

    private void drawNetworkStatus(Graphics2D g2d, int x, int y) {
        g2d.setColor(new Color(0, 255, 0, 180));
        g2d.drawString("NETWORK:", x, y);

        // 绘制网络活动波形
        int[] values = new int[50];
        for (int i = 0; i < values.length; i++) {
            values[i] = random.nextInt(40);
        }

        for (int i = 0; i < values.length - 1; i++) {
            g2d.drawLine(x + i * 4, y + 20 + values[i],
                    x + (i + 1) * 4, y + 20 + values[i + 1]);
        }
    }

    // 添加持续循环的消息集合
    private String[][] messageSets = {
            {
                    "[网络扫描] 检测到新目标: %ip%",
                    "[漏洞扫描] 正在使用Nessus扫描...",
                    "[系统识别] 发现目标操作系统: %os%",
                    "[端口扫描] 开放端口: %ports%",
                    "[服务识别] 发现Web服务: Apache %version%"
            },
            {
                    "[攻击模块] 正在测试SQL注入漏洞...",
                    "[数据库] 发现%database%数据库",
                    "[密码破解] 正在使用字典攻击...",
                    "[防火墙] 检测到%firewall%防火墙",
                    "[绕过尝试] 正在使用高级技术绕过..."
            },
            {
                    "[内网探测] 发现内网段: %subnet%",
                    "[横向移动] 尝试远程执行命令...",
                    "[权限提升] 利用内核漏洞...",
                    "[后门安装] 正在植入持久化后门...",
                    "[日志清理] 清除攻击痕迹..."
            }
    };

    private String getRandomOS() {
        String[] os = {"Windows Server 2019", "Ubuntu 20.04 LTS", "CentOS 8", "Debian 11", "Red Hat Enterprise 8"};
        return os[random.nextInt(os.length)];
    }

    private String getRandomPorts() {
        StringBuilder ports = new StringBuilder();
        for (int i = 0; i < 3; i++) {
            ports.append(random.nextInt(65535)).append(", ");
        }
        return ports.toString().substring(0, ports.length() - 2);
    }

    private String getRandomDatabase() {
        String[] dbs = {"MySQL", "PostgreSQL", "Oracle", "MongoDB", "SQL Server"};
        return dbs[random.nextInt(dbs.length)] + " " + random.nextInt(10) + "." + random.nextInt(10);
    }

    private String getRandomFirewall() {
        String[] firewalls = {"Cisco ASA", "Fortinet", "Palo Alto", "CheckPoint", "Sophos"};
        return firewalls[random.nextInt(firewalls.length)];
    }

    private String formatMessage(String message) {
        message = message.replace("%ip%", generateRandomIP());
        message = message.replace("%os%", getRandomOS());
        message = message.replace("%ports%", getRandomPorts());
        message = message.replace("%version%", random.nextInt(10) + "." + random.nextInt(10));
        message = message.replace("%database%", getRandomDatabase());
        message = message.replace("%firewall%", getRandomFirewall());
        message = message.replace("%subnet%", "192.168." + random.nextInt(256) + ".0/24");
        return message;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            HackerConsole console = new HackerConsole();
            console.setVisible(true);

            // 创建持续输出的定时器
            Timer continuousTimer = new Timer(1000, null); // 加快输出速度
            continuousTimer.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 获取当前消息集合
                    String[] currentMessages = console.messageSets[console.currentMessageSet];

                    // 随机选择并显示消息
                    String message = currentMessages[console.random.nextInt(currentMessages.length)];
                    console.printMessage(console.formatMessage(message));

                    // 添加进度条或其他技术细节
                    if (console.random.nextInt(3) == 0) {
                        console.printMessage(console.generateProgressBar(console.random.nextInt(100), console.random.nextInt(3)));
                    }

                    // 循环切换消息集合
                    console.currentMessageSet = (console.currentMessageSet + 1) % console.messageSets.length;
                }
            });
            continuousTimer.start();

            // 在main方法中添加动态更新效果
            Timer statusTimer = new Timer(100, e -> {
                console.matrixPanel.repaint();
            });
            statusTimer.start();
        });
    }
}